const Router = require('koa-router');
const mongoose = require('mongoose');
const path = require('path');
const py = require('pyfl').default;
let router = new Router();

// 商品分类新增
router.post('/newcategory', async (ctx,next) => {
  const Category = mongoose.model('Category');
  let categoryInfo = ctx.request.body;
  ctx.status=200;
  let category = await Category.findOne({
    name: categoryInfo.name,
  }).exec();
  if(!category){
    const newCategory = new Category({
      name: categoryInfo.name,
      desciption: categoryInfo.desciption,
      createAt: new Date(),
    });
    let saveRes = await newCategory.save();
    if(saveRes) {
      ctx.body = {
        code: 200,
        message: "新增类品成功",
      }
    } else {
      ctx.body = {
        code: 500,
        message: "服务器错误",
      }
    }
  } else {
    ctx.body = {
      code: 400,
      message: "类品名已存在"
    }
  }
  await next();
})

// 查询所有分类
router.get('/getallcategory',async (ctx,next) => {
  const Category = mongoose.model('Category');
  let categoryName = ctx.request.query.categoryName;
  let whereStr = {'name': {$regex: new RegExp(categoryName,'i')}};
  let list = await Category.find(whereStr,{name: 1,_id: 1,desciption: 1,createAt: 1}).exec();
  list=list.map((item,index) => {
    return {
      id: index + 1,
      code: item._doc._id,
      codeName: item._doc.name,
      ...item._doc
    }
  })
  ctx.status=200;
  ctx.body = {
    code: 200,
    data: list,
    message: "操作成功",
  }
  await next();
})

// 查询分类
router.get('/getcategorylist', async (ctx,next) => {
  const Category = mongoose.model('Category');
  console.log(ctx.request.query);
  let {pageNum = 1, pageSize = 10} = ctx.request.query;
  ctx.status=200;
  console.log(pageNum);
  let total = await Category.countDocuments();
  let list = await Category.find({},{name: 1,desciption: 1,_id: 1}).skip((pageNum - 1) * pageSize).limit(pageSize*1).exec();
  // console.log(total)
  console.log(list);
  list=list.map((item,index) => {
    return {
      id: (pageNum-1)*pageSize + index + 1,
      ...item._doc
    }
  })
  ctx.body = {
    code: 200,
    data: list,
    total,
    pageNum,
    pageSize,
    message: "操作成功",
  }
  await next();
})

// 编辑分类
router.post('/editcategory', async (ctx,next) => {
  const Category = mongoose.model('Category');
  let categoryInfo = ctx.request.body;
  console.log(categoryInfo);
  ctx.status=200;
  const editRes = await Category.findByIdAndUpdate(categoryInfo._id,{$set: {name: categoryInfo.name,desciption: categoryInfo.desciption}});
  console.log(editRes);
  if(editRes) {
    ctx.body = {
      code: 200,
      message: "更改成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 删除分类
router.post('/removecategory', async (ctx,next) => {
  const Category = mongoose.model('Category');
  let categoryInfo = ctx.request.body;
  console.log(categoryInfo);
  ctx.status=200;
  const editRes = await Category.remove({_id: { $in: categoryInfo.ids }});
  console.log(editRes);
  if(editRes.ok>=1) {
    ctx.body = {
      code: 200,
      message: "删除成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 商品风格新增
router.post('/newstyle', async (ctx,next) => {
  const Style = mongoose.model('Style');
  let styleInfo = ctx.request.body;
  ctx.status=200;
  let style = await Style.findOne({
    name: styleInfo.name,
  }).exec();
  if(!style){
    const newStyle = new Style({
      name: styleInfo.name,
      desciption: styleInfo.desciption,
      createAt: new Date(),
    });
    let saveRes = await newStyle.save();
    if(saveRes) {
      ctx.body = {
        code: 200,
        message: "新增风格成功",
      }
    } else {
      ctx.body = {
        code: 500,
        message: "服务器错误",
      }
    }
  } else {
    ctx.body = {
      code: 400,
      message: "风格名已存在"
    }
  }
  await next();
})

// 查询所有风格
router.get('/getallstyle',async (ctx,next) => {
  const Style = mongoose.model('Style');
  let styleName = ctx.request.query.styleName;
  let whereStr = {'name': {$regex: new RegExp(styleName,'i')}};
  let list = await Style.find(whereStr,{name: 1,desciption: 1,_id: 1,desciption: 1,createAt: 1}).exec();
  list=list.map((item,index) => {
    return {
      id: index + 1,
      code: item._doc._id,
      codeName: item._doc.name,
      ...item._doc
    }
  })
  ctx.status=200;
  ctx.body = {
    code: 200,
    data: list,
    message: "操作成功",
  }
  await next();
})

// 查询风格
router.get('/getstylelist', async (ctx,next) => {
  const Style = mongoose.model('Style');
  let {pageNum = 1, pageSize = 10} = ctx.request.query;
  ctx.status=200;
  let total = await Style.countDocuments();
  let list = await Style.find({},{name: 1,desciption: 1,_id: 1}).skip((pageNum - 1) * pageSize).limit(pageSize*1).exec();
  list=list.map((item,index) => {
    return {
      id: (pageNum-1)*pageSize + index + 1,
      ...item._doc
    }
  })
  ctx.body = {
    code: 200,
    data: list,
    total,
    pageNum,
    pageSize,
    message: "操作成功",
  }
  await next();
})

// 编辑风格
router.post('/editstyle', async (ctx,next) => {
  const Style = mongoose.model('Style');
  let styleInfo = ctx.request.body;
  ctx.status=200;
  const editRes = await Style.findByIdAndUpdate(styleInfo._id,{$set: {name: styleInfo.name,desciption: styleInfo.desciption}});
  if(editRes) {
    ctx.body = {
      code: 200,
      message: "更改成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 删除风格
router.post('/removestyle', async (ctx,next) => {
  const Style = mongoose.model('Style');
  let styleInfo = ctx.request.body;
  console.log(styleInfo);
  ctx.status=200;
  const editRes = await Style.remove({_id: { $in: styleInfo.ids }});
  console.log(editRes);
  if(editRes.ok>=1) {
    ctx.body = {
      code: 200,
      message: "删除成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 商品产家新增
router.post('/newfactory', async (ctx,next) => {
  const Factory = mongoose.model('Factory');
  let factoryInfo = ctx.request.body;
  ctx.status=200;
  let factory = await Factory.findOne({
    name: factoryInfo.name,
  }).exec();
  if(!factory){
    const newFactory = new Factory({
      name: factoryInfo.name,
      desciption: factoryInfo.desciption,
      contact: factoryInfo.contact,
      origin: factoryInfo.origin,
      createAt: new Date(),
    });
    let saveRes = await newFactory.save();
    if(saveRes) {
      ctx.body = {
        code: 200,
        message: "新增工厂成功",
      }
    } else {
      ctx.body = {
        code: 500,
        message: "服务器错误",
      }
    }
  } else {
    ctx.body = {
      code: 400,
      message: "工厂名已存在"
    }
  }
  await next();
})

// 查询所有工厂
router.get('/getallfactory',async (ctx,next) => {
  const Factory = mongoose.model('Factory');
  let factoryName = ctx.request.query.factoryName;
  let whereStr = {'name': {$regex: new RegExp(factoryName,'i')}};
  let list = await Factory.find(whereStr,{name: 1,desciption: 1,_id: 1,contact: 1,origin: 1,createAt: 1}).exec();
  list=list.map((item,index) => {
    return {
      id: index + 1,
      code: item._doc._id,
      codeName: item._doc.name,
      ...item._doc
    }
  })
  ctx.status=200;
  ctx.body = {
    code: 200,
    data: list,
    message: "操作成功",
  }
  await next();
})

// 查询工厂
router.get('/getfactorylist', async (ctx,next) => {
  const Factory = mongoose.model('Factory');
  let {pageNum = 1, pageSize = 10} = ctx.request.query;
  ctx.status=200;
  let total = await Factory.countDocuments();
  let list = await Factory.find({},{name: 1,desciption: 1,_id: 1,contact: 1,origin: 1,createAt: 1}).skip((pageNum - 1) * pageSize).limit(pageSize*1).exec();
  list=list.map((item,index) => {
    return {
      id: (pageNum-1)*pageSize + index + 1,
      ...item._doc
    }
  })
  ctx.body = {
    code: 200,
    data: list,
    total,
    pageNum,
    pageSize,
    message: "操作成功",
  }
  await next();
})

// 编辑工厂
router.post('/editfactory', async (ctx,next) => {
  const Factory = mongoose.model('Factory');
  let factoryInfo = ctx.request.body;
  ctx.status=200;
  const editRes = await Factory.findByIdAndUpdate(factoryInfo._id,{$set: {name: factoryInfo.name,desciption: factoryInfo.desciption,contact: factoryInfo.contact,origin: factoryInfo.origin}});
  if(editRes) {
    ctx.body = {
      code: 200,
      message: "更改成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 删除工厂
router.post('/removefactory', async (ctx,next) => {
  const Factory = mongoose.model('Factory');
  let factoryInfo = ctx.request.body;
  console.log(factoryInfo);
  ctx.status=200;
  const editRes = await Factory.remove({_id: { $in: factoryInfo.ids }});
  console.log(editRes);
  if(editRes.ok>=1) {
    ctx.body = {
      code: 200,
      message: "删除成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 查询商品
router.get('/getgoodsList', async (ctx,next) => {
  console.log(`http://localhost:3000/uploads/`+'12321');
  const Goods = mongoose.model('Goods');
  let {pageNum = 1, pageSize = 10} = ctx.request.query;
  ctx.status=200;
  let total = await Goods.countDocuments();
  let list = await Goods.find({},{}).skip((pageNum - 1) * pageSize).limit(pageSize*1).populate('style').populate('category').populate('picId').populate('factory').exec();
  list=list.map((item,index) => {
    return {
      id: (pageNum-1)*pageSize + index + 1,
      ...item._doc
    }
  })
  ctx.body = {
    code: 200,
    data: list,
    total,
    pageNum,
    pageSize,
    message: "操作成功",
  }
  await next();
})
// 商品图上传


// 商品编辑
router.post('/editgoods', async (ctx, next) => {
  const Goods = mongoose.model('Goods');
  const Style = mongoose.model('Style');
  const Category = mongoose.model('Category');
  const goodsInfo = ctx.request.body;
  const categoryInfo = await Category.findById(goodsInfo.categoryId);
  const styleInfo = await Style.findById(goodsInfo.style);
  ctx.status= 200;
  let total = await Goods.countDocuments({category: goodsInfo.categoryId, style: goodsInfo.style});
  const goodsNo = py(categoryInfo.name[0])[0]+py(styleInfo.name[0])[0]+(total+1);
  const feed = goodsInfo.feed.map((item,index) => {
    if(item && goodsInfo.feedprice[index]) {
      return ({
        "feed": item,
        "feedprice": goodsInfo.feedprice[index],
      })
    } else {
      return null;
    }   
  }).filter(Boolean);
  const editRes = await Goods.findByIdAndUpdate(goodsInfo._id,{
    no: goodsNo,
    name: goodsInfo.name,
    category: goodsInfo.categoryId,
    size: goodsInfo.size,
    texture: goodsInfo.texture,
    factory: goodsInfo.factory,
    picId: goodsInfo.goodspic,
    feed: feed,
    price: goodsInfo.price,
    inPrice: goodsInfo.inPrice,
    remark: goodsInfo.remark,
    style: goodsInfo.style,
    desciption: goodsInfo.desciption,
    status: goodsInfo.status,
    saleStatus: goodsInfo.saleStatus,
  });
  if(editRes) {
    ctx.body = {
      code: 200,
      message: "更改成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 商品删除
router.post('/removegoods', async (ctx,next) => {
  const Goods = mongoose.model('Goods');
  let goodsInfo = ctx.request.body;
  console.log(goodsInfo);
  ctx.status=200;
  const editRes = await Goods.remove({_id: { $in: goodsInfo.ids }});
  console.log(editRes);
  if(editRes.ok>=1) {
    ctx.body = {
      code: 200,
      message: "删除成功"
    }
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败"
    }
  }
  await next();
})

// 商品新增
router.post('/newgoods', async (ctx, next) => {
  const Goods = mongoose.model('Goods');
  const TempPic = mongoose.model('TempPic');
  const Style = mongoose.model('Style');
  const Category = mongoose.model('Category');
  const goodsInfo = ctx.request.body;
  const categoryInfo = await Category.findById(goodsInfo.categoryId);
  const styleInfo = await Style.findById(goodsInfo.style);
  ctx.status= 200;
  let total = await Goods.countDocuments({category: goodsInfo.categoryId, style: goodsInfo.style});
  console.log(total);
  const goodsNo = py(categoryInfo.name[0])[0]+py(styleInfo.name[0])[0]+(total+1);
  const feed = goodsInfo.feed.map((item,index) => {
    if(item && goodsInfo.feedprice[index]) {
      return ({
        "feed": item,
        "feedprice": goodsInfo.feedprice[index],
      })
    } else {
      return null;
    }   
  }).filter(Boolean);
  const newGoods = new Goods({
    no: goodsNo,
    name: goodsInfo.name,
    category: goodsInfo.categoryId,
    size: goodsInfo.size,
    texture: goodsInfo.texture,
    factory: goodsInfo.factory,
    picId: goodsInfo.goodspic,
    feed: feed,
    price: goodsInfo.price,
    inPrice: goodsInfo.inPrice,
    remark: goodsInfo.remark,
    style: goodsInfo.style,
    desciption: goodsInfo.desciption,
    status: goodsInfo.status,
    saleStatus: goodsInfo.saleStatus,
  });
  const saveRes = await newGoods.save();
  if(saveRes) {
    ctx.body = {
      code: 200,
      message: "新增商品成功",
    }
  } else {
    ctx.body = {
      code: 500,
      message: "服务器错误",
    } 
  }
  await next();
})


module.exports = router;